<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Konva Control Layer Position Example</title>
  <script src="https://unpkg.com/konva@8/konva.min.js"></script>
  <style>
    body {
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      background-color: #f0f0f0;
    }
  </style>
</head>

<body>
  <div id="container"></div>
  <script>
    // 创建舞台
    const stage = new Konva.Stage({
      container: 'container',
      width: window.innerWidth,
      height: window.innerHeight
    })

    stage.container().addEventListener("drop", (e) => {
      e.preventDefault()

      console.log('%c [  ]-35', 'font-size:13px; background:pink; color:#bf2c9f;', e)
    })
    // 创建层
    const layer = new Konva.Layer()
    stage.add(layer)

    // 创建一个矩形
    const rect = new Konva.Rect({
      x: 100,
      y: 100,
      width: 200,
      height: 100,
      fill: 'red',
      draggable: true
    })
    layer.add(rect)

    // 绘制层
    layer.draw()

    // 处理滚轮事件
    stage.on('wheel', function (event) {
      event.evt.preventDefault()
      const scaleBy = 1.05
      const oldScale = stage.scaleX()
      const mousePointTo = {
        x: stage.getPointerPosition().x / oldScale - stage.x() / oldScale,
        y: stage.getPointerPosition().y / oldScale - stage.y() / oldScale
      }

      const newScale = event.evt.deltaY > 0 ? oldScale * scaleBy : oldScale / scaleBy

      stage.scale({ x: newScale, y: newScale })

      const newPos = {
        x: -(mousePointTo.x - stage.getPointerPosition().x / newScale) * newScale,
        y: -(mousePointTo.y - stage.getPointerPosition().y / newScale) * newScale
      }

      // console.log('%c [  ]-69', 'font-size:13px; background:pink; color:#bf2c9f;', newPos)
      stage.position(newPos)
      stage.batchDraw()
    })
    // 监听鼠标移动事件
    stage.on('mousemove', function () {
      const scaleX = stage.scaleX()
      const pointerPosition = stage.getPointerPosition()
      // console.log('Scale X:', stage.scale())
      // console.log('Pointer Position:', pointerPosition)
    })

    // 限制矩形不超出舞台边界
    rect.on('dragmove', function () {
      const stageWidth = stage.width()
      const stageHeight = stage.height()
      const rectWidth = rect.width()
      const rectHeight = rect.height()

      let newX = rect.x()
      let newY = rect.y()

      if (newX < 0) {
        newX = 0
      } else if (newX + rectWidth > stageWidth) {
        newX = stageWidth - rectWidth
      }

      if (newY < 0) {
        newY = 0
      } else if (newY + rectHeight > stageHeight) {
        newY = stageHeight - rectHeight
      }

      rect.position({ x: newX, y: newY })
    });
  </script>
</body>

</html>